package com.example.concurrentprogramming8016.future.completionfuture;

import java.util.concurrent.*;

/**
 * @author liyanhao
 * @Date 2023-01-08 17:02
 * 电商询价流程
 */
public class CompletionServiceDemo {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        //创建CompletionService
        CompletionService<Integer> cs = new ExecutorCompletionService<>(threadPool);
        //向每个商品进行异步询价
        cs.submit(() -> getPriceByS1());
        cs.submit(() -> getPriceByS2());
        cs.submit(() -> getPriceByS3());
        // 将询价结果异步保存到数据库
        for (int i = 0; i < 3; i++) {
            //从阻塞队列获取futuretask
            Integer integer = cs.take().get();
            threadPool.execute(() -> save(integer));
        }
        threadPool.shutdown();
    }

    private static void save(Integer integer) {
        System.out.println("保存询价结果:" + integer);
    }
    private static Integer getPriceByS1() throws InterruptedException {
        TimeUnit.SECONDS.sleep(1);
        System.out.println("电商S1询价结果是12000");
        return 12000;
    }
    private static Integer getPriceByS2() throws InterruptedException {
        TimeUnit.SECONDS.sleep(1);
        System.out.println("电商S2询价结果是12001");
        return 12001;
    }
    private static Integer getPriceByS3() throws InterruptedException {
        TimeUnit.SECONDS.sleep(1);
        System.out.println("电商S3询价结果是12002");
        return 12002;
    }
}
